<template>
  <div :class="['search', isFold && 'isFold']">
    <div class="search__content" ref="searchContentRef">
      <slot></slot>
    </div>
    <div class="search__btn">
      <el-button @click="reset">重置</el-button>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button v-if="showMore" @click="toggleMore"> {{ isFold ? "展开" : "收起" }}更多 </el-button>
    </div>
  </div>

  <div class="line"></div>
</template>
<script lang="ts" setup>
import { ref, defineEmits, onMounted, onActivated } from "vue"
import { onBeforeRouteLeave } from "vue-router"

const emits = defineEmits(["reset", "search"])
const isFold = ref(false)
const searchContentRef = ref<any>(null)
const showMore = ref(false)

const toggleMore = () => {
  isFold.value = !isFold.value
}

const search = () => {
  emits("search")
}

const reset = () => {
  emits("reset")
}

const handleResize = () => {
  if (searchContentRef.value?.offsetHeight > 72) {
    showMore.value = true
  } else {
    showMore.value = false
  }
}

onMounted(() => {
  handleResize()
  window.addEventListener("resize", handleResize)
})

onActivated(() => {
  window.addEventListener("resize", handleResize)
})

onBeforeRouteLeave(() => {
  window.removeEventListener("resize", handleResize)
})
</script>

<style lang="scss" scoped>
.search {
  display: grid;
  grid-template-columns: 1fr auto;
  align-items: baseline;
  background: #fff;
  padding: 10px 0;
  overflow: hidden;

  &__content {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    grid-gap: 20px;
    margin-right: 10px;

    :deep(> div) {
      display: flex;
      align-items: center;

      label {
        padding-left: 6px;
        background: #fafafa;
        border: 1px solid #d9d9d9;
        border-right: none;
        width: 100px;
        height: 32px;
        line-height: 32px;
        font-size: 12px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        border-radius: 4px 0 0 4px;
      }

      > div {
        width: 100% !important;

        .el-input__wrapper {
          border-top-left-radius: 0px;
          border-bottom-left-radius: 0px;
        }
      }
    }
  }

  &__btn {
    display: flex;
    justify-content: flex-end;
    > * {
      margin: 0 2px;
    }
  }
}
.isFold {
  height: 50px;
}
</style>
